import React from 'react';
import PropTypes from 'prop-types';
import {getDetail, approvePartOrderPlanPass, approvePartOrderPlanReject} from './api';
import styles from './style.css';
import {hasPermissions} from './utils';
import {PERMISSIONS} from './constants';
import {approveValidator, addOrUpdateValidator} from './validator';
import {Form, Spin, Card, Button, Row, Col, Table} from 'antd';
import {FORM_OPTIONS, DATETIME_FORMAT, FORM_ROW_OPTIONS} from '../constants';
import TextInput from 'Shared/components/TextInput';
import FormItem from 'antd/lib/form/FormItem';
import {injectIntl, formatMessage} from './intl';
import Return from '../common/Return';
import {currency} from '../Enum';
import {conventEnumValueToString, formatDateTime, formatAmount} from '../utils';
import DescriptionList from 'ant-design-pro/lib/DescriptionList';
import Ellipsis from 'ant-design-pro/lib/Ellipsis';
const {Description} = DescriptionList;

class ApprovePanel extends React.PureComponent {
    state = {
        loading: false,
        data: {},
        details: [],
    }
    componentDidMount() {
        if(this.props.id)
            this.getDetailInfo();
    }
    componentWillUnmount() {
        this.isunmount = true;
    }
    getDetailInfo = () => {
        const id = this.props.id;
        this.setState({loading: true});
        getDetail(id)
            .then(res => {
                if(res.ok)
                    this.setState({
                        loading: false,
                        data: res.data,
                        details: res.data.details.map(v => Object.assign({}, v, {
                            isDealerUser: this.props.isDealerUser
                        }))
                    });
                else
                    this.setState({
                        loading: false
                    });
            });
    }
    setRowClassName(record) {
        if(record.isEstimated && !record.isDealerUser)
            return styles.rowStyle;
    }
    onClickApprovePassBtn = () => {
        const {data, details} = this.state;
        const isValid = approveValidator(data) && addOrUpdateValidator(details);
        if(!isValid) {
            this.setState({
                validate: true,
                loading: false
            });
            return;
        }
        this.setState({loading: true});
        approvePartOrderPlanPass(data.id, {
            approvedContent: data.approvedContent,
            rowVersion: data.rowVersion}).then(res => {
            this.setState({loading: false});
            if(res.ok)
                this.props.successReturn();
        });
    }
    onClickApproveRejectBtn = () => {
        const {data, details} = this.state;
        const isValid = approveValidator(data) && addOrUpdateValidator(details);
        if(!isValid) {
            this.setState({
                validate: true,
                loading: false
            });
            return;
        }
        this.setState({loading: true});
        approvePartOrderPlanReject(data.id, {
            approvedContent: data.approvedContent,
            rowVersion: data.rowVersion}).then(res => {
            this.setState({loading: false});
            if(res.ok)
                this.props.successReturn();
        });
    }
    onChange = (value, name) => {
        const data = Object.assign({}, this.state.data, {
            [name]: value
        });
        this.setState({
            data,
            hasOperat: true
        });
    }
    render() {
        const {data, details} = this.state;
        const validateApprovedContent = ((data.approvedContent && data.approvedContent.length > 200) || !data.approvedContent) && this.state.validate ? 'error' : null;
        const totalVariety = this.state.details.filter(o => o.n2Quantity > 0 || o.n3Quantity > 0 || o.n4Quantity > 0).length;
        const totalN2Variety = this.state.details.filter(o => o.n2Quantity > 0).length;
        const totalN3Variety = this.state.details.filter(o => o.n3Quantity > 0).length;
        const totalN4Variety = this.state.details.filter(o => o.n4Quantity > 0).length;
        let totalQuantity = 0;
        let totalN2Quantity = 0;
        let totalN3Quantity = 0;
        let totalN4Quantity = 0;
        let totalFee = 0;
        let totalN2Fee = 0;
        let totalN3Fee = 0;
        let totalN4Fee = 0;
        this.state.details.forEach(o => {
            totalQuantity += (o.n2Quantity + o.n3Quantity + o.n4Quantity);
            totalN2Quantity += o.n2Quantity;
            totalN3Quantity += o.n3Quantity;
            totalN4Quantity += o.n4Quantity;
            totalFee += (o.n2Quantity + o.n3Quantity + o.n4Quantity) * o.price;
            totalN2Fee += o.n2Quantity * o.price;
            totalN3Fee += o.n3Quantity * o.price;
            totalN4Fee += o.n4Quantity * o.price;
        });

        const colums = [{
            title: formatMessage({
                id: 'approvePanel.column.partCode',
                defaultMessage: '备件编号'
            }),
            width: 200,
            dataIndex: 'partCode',
        }, {
            title: formatMessage({
                id: 'approvePanel.column.partName',
                defaultMessage: '备件名称'
            }),
            dataIndex: 'partName',
            width: 350,
            render: text => <Ellipsis tooltip fullWidthRecognition length={36}>{text}</Ellipsis>
        }, {
            title: formatMessage({
                id: 'approvePanel.column.productCategoryCode',
                defaultMessage: '适用车型'
            }),
            width: 200,
            dataIndex: 'productCategoryCode',
            render: text => <Ellipsis tooltip fullWidthRecognition length={20}>{text}</Ellipsis>
        }, {
            title: formatMessage({
                id: 'approvePanel.column.minPackSize',
                defaultMessage: '最小包装数'
            }),
            width: 100,
            dataIndex: 'minPackSize',
            
        }, {
            title: formatMessage({
                id: 'approvePanel.column.unit',
                defaultMessage: '计量单位'
            }),
            width: 100,
            dataIndex: 'unit',
        }, {
            title: formatMessage({
                id: 'approvePanel.column.n2Quantity',
                defaultMessage: 'N+2月订购数量'
            }),
            width: 180,
            dataIndex: 'n2Quantity'
        }, {
            title: formatMessage({
                id: 'approvePanel.column.n3Quantity',
                defaultMessage: 'N+3月订购数量'
            }),
            width: 180,
            dataIndex: 'n3Quantity'
        }, {
            title: formatMessage({
                id: 'approvePanel.column.n4Quantity',
                defaultMessage: 'N+4月订购数量'
            }),
            width: 200,
            dataIndex: 'n4Quantity'
        }, {
            title: formatMessage({
                id: 'approvePanel.column.price',
                defaultMessage: '备件单价'
            }),
            width: 150,
            dataIndex: 'price',
            render: text => formatAmount(text)
        }, {
            title: formatMessage({
                id: 'approvePanel.column.partOutQuantity',
                defaultMessage: '月均消耗'
            }),
            width: 250,
            dataIndex: 'partOutQuantity',
            render: text => formatAmount(text)
        }, {
            title: formatMessage({
                id: 'approvePanel.column.stockQuantity',
                defaultMessage: '上月总代库存'
            }),
            width: 250,
            dataIndex: 'stockQuantity'
        }, {
            title: formatMessage({
                id: 'approvePanel.column.partReplacementCode',
                defaultMessage: '替换件编号'
            }),
            width: 250,
            dataIndex: 'partReplacementCode'
        }, {
            title: formatMessage({
                id: 'approvePanel.column.replacementQuantity',
                defaultMessage: '替换件总代库存'
            }),
            width: 280,
            dataIndex: 'replacementQuantity'
        }];
        const submitable = !hasPermissions(PERMISSIONS.approve, this.props.permission);
        return (
            <div className="form-standard">
                <Spin spinning={this.state.loading}>
                    <Form>
                        <Card title={formatMessage({
                            id: 'approvePanel.column.partOrderPlan',
                            defaultMessage: '备件需求计划单'
                        })}>
                            <Row>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'approvePanel.operation.code',
                                        defaultMessage: '编号'
                                    })} {...FORM_OPTIONS.item}>
                                        {data.code}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'approvePanel.operation.dealerCode',
                                        defaultMessage: '总代编号'
                                    })} {...FORM_OPTIONS.item}>
                                        {data.dealerCode}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'approvePanel.operation.dealerName',
                                        defaultMessage: '总代名称'
                                    })} {...FORM_OPTIONS.item}>
                                        {data.dealerName}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'approvePanel.operation.brandCode',
                                        defaultMessage: '品牌编号'
                                    })} {...FORM_OPTIONS.item}>
                                        {data.brandCode}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'approvePanel.operation.brandName',
                                        defaultMessage: '品牌名称'
                                    })} {...FORM_OPTIONS.item}>
                                        {data.brandName}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'approvePanel.operation.country',
                                        defaultMessage: '国家/地区'
                                    })} {...FORM_OPTIONS.item}>
                                        {data.country}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'approvePanel.operation.orderPlanYear',
                                        defaultMessage: '计划年份'
                                    })} {...FORM_OPTIONS.item}>
                                        {data.orderPlanYear}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'approvePanel.operation.orderPlanMonth',
                                        defaultMessage: '计划月份'
                                    })} {...FORM_OPTIONS.item}>
                                        {data.orderPlanMonth}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'approvePanel.operation.currency',
                                        defaultMessage: '币种'
                                    })}{...FORM_OPTIONS.item}>
                                        {conventEnumValueToString(currency, data.currency)}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem className={styles.multiLabel} label={formatMessage({
                                        id: 'approvePanel.operation.totalFee',
                                        defaultMessage: '总金额'
                                    })}{...FORM_OPTIONS.item}>
                                        {formatAmount(totalFee)}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'approvePanel.operation.totalQuantity',
                                        defaultMessage: '总数量'
                                    })}{...FORM_OPTIONS.item}>
                                        {totalQuantity || ''}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'approvePanel.operation.totalVariety',
                                        defaultMessage: '总品种数'
                                    })}{...FORM_OPTIONS.item}>
                                        {totalVariety || ''}
                                    </FormItem>
                                </Col>
                            </Row>
                            <Row>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'approvePanel.operation.createTime',
                                        defaultMessage: '提报日期'
                                    })}{...FORM_OPTIONS.item}>
                                        {formatDateTime(data.createTime, DATETIME_FORMAT)}
                                    </FormItem>
                                </Col>
                            </Row>
                            <Row>
                                <Col {...FORM_ROW_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'approvePanel.operation.remark',
                                        defaultMessage: '备注'
                                    })} {...FORM_ROW_OPTIONS.item}>
                                        {data.remark}
                                    </FormItem>
                                </Col>
                            </Row>
                            <Row>
                                <Col>
                                    <FormItem label={formatMessage({
                                        id: 'approvePanel.operation.approvedContent',
                                        defaultMessage: '审核意见'
                                    })} {...FORM_ROW_OPTIONS.item}
                                    validateStatus={validateApprovedContent}
                                    required>
                                        <TextInput
                                            type="textarea"
                                            name="approvedContent"
                                            value={data.approvedContent}
                                            onBlur={this.onChange} />
                                    </FormItem>
                                </Col>
                            </Row>
                        </Card>
                        <Card
                            title={formatMessage({
                                id: 'editPanel.card.title.detail',
                                defaultMessage: '备件需求计划清单'
                            })}>
                            <Table
                                className="white-space-nowrap"
                                rowKey="id"
                                columns={colums}
                                dataSource={details}
                                rowClassName={this.setRowClassName}
                                pagination={false}
                                scroll={{
                                    x: 'max-content',
                                    y: 600
                                }}
                                size="small"
                                bordered={true}
                                footer={() => <div>
                                    <Row className={styles.alertMargin}>
                                        <DescriptionList>
                                            <Description term={formatMessage({
                                                id: 'newPanel.operation.totalN2Quantity',
                                                defaultMessage: 'N+2月订购数量汇总'
                                            })}>{totalN2Quantity}
                                            </Description>
                                            <Description term={formatMessage({
                                                id: 'newPanel.operation.totalN3Quantity',
                                                defaultMessage: 'N+3月订购数量汇总'
                                            })}>{totalN3Quantity}
                                            </Description>
                                            <Description term={formatMessage({
                                                id: 'newPanel.operation.totalN4Quantity',
                                                defaultMessage: 'N+4月订购数量汇总'
                                            })}>{totalN4Quantity}
                                            </Description>
                                        </DescriptionList>
                                    </Row>
                                    <Row className={styles.alertMargin}>
                                        <DescriptionList>
                                            <Description term={formatMessage({
                                                id: 'newPanel.operation.totalN2Fee',
                                                defaultMessage: 'N+2月订购金额汇总'
                                            })}>{formatAmount(totalN2Fee)}
                                            </Description>
                                            <Description term={formatMessage({
                                                id: 'newPanel.operation.totalN3Fee',
                                                defaultMessage: 'N+3月订购金额汇总'
                                            })}>{formatAmount(totalN3Fee)}
                                            </Description>
                                            <Description term={formatMessage({
                                                id: 'newPanel.operation.totalN4Fee',
                                                defaultMessage: 'N+4月订购金额汇总'
                                            })}>{formatAmount(totalN4Fee)}
                                            </Description>
                                        </DescriptionList>
                                    </Row>
                                    <Row className={styles.alertMargin}>
                                        <DescriptionList>
                                            <Description term={formatMessage({
                                                id: 'newPanel.operation.totalN2Variety',
                                                defaultMessage: 'N+2月订购品种汇总'
                                            })}>{totalN2Variety}
                                            </Description>
                                            <Description term={formatMessage({
                                                id: 'newPanel.operation.totalN3Variety',
                                                defaultMessage: 'N+3月订购品种汇总'
                                            })}>{totalN3Variety}
                                            </Description>
                                            <Description term={formatMessage({
                                                id: 'newPanel.operation.totalN4Variety',
                                                defaultMessage: 'N+4月订购品种汇总'
                                            })}>{totalN4Variety}
                                            </Description>
                                        </DescriptionList>
                                    </Row>
                                </div>} />
                        </Card>
                        <Card className={styles.optionBtn}>
                            <Button
                                onClick={this.onClickApproveRejectBtn}
                                disabled={!submitable}
                                loading={this.state.loading}>
                                {formatMessage({
                                    id: 'approvePanel.operation.onSubmitReject',
                                    defaultMessage: '驳回'
                                })}
                            </Button>
                            <Button
                                type="primary"
                                onClick={this.onClickApprovePassBtn}
                                disabled={!submitable}
                                loading={this.state.loading}>
                                {formatMessage({
                                    id: 'approvePanel.operation.onSubmiPass',
                                    defaultMessage: '审核通过'
                                })}
                            </Button>
                        </Card>
                    </Form>
                </Spin>
                <div className="page-toolbar">
                    <Return
                        disabled={this.state.loading}
                        showWarning={this.state.hasOperat}
                        onConfirm={this.props.onCancel} />
                </div>
            </div>
        );
    }
}

ApprovePanel.propTypes = {
    permission: PropTypes.array.isRequired,
    successReturn: PropTypes.func.isRequired,
    onCancel: PropTypes.func.isRequired,
    history: PropTypes.object,
    isDealerUser: PropTypes.bool
};

import {connect} from 'react-redux';
import routes from './routes';
import {
    tableSearch,
} from './actions';
import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';
const getPermissions = selectorFactory(['page', 'domainData', 'permission', 'data']);
const mapStateToProps = state => ({
    isDealerUser: state.getIn((['page', 'domainData', 'initData', 'isDealerUser'])),
    permission: getPermissions(state),
});

const mapDispatchToProps = (dispatch, props) => ({
    successReturn: () => {
        dispatch(tableSearch());
        props.history.push(routes.query.url());
    },
    onCancel: () => {
        props.history.push(routes.query.url());
    },
});
export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(ApprovePanel));
